/*
 ============================================================================
 Name        : phase_para.c
 Author      : chenf
 Version     :
 Copyright   : loongsec
 Description : CRUD phase_parm table, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include "sqlite3.h"
#include "cgi.h"
#include "cookie.h"
#include "stdx.h"

void put_json(char **azResult, int nrow, int ncolumn);
void put_html(char **azResult, int nrow, int ncolumn);

void put_error(char *err_msg){
    printf("Content-type:text/html;charset=UTF-8\n\n");
	printf("%s.\n", err_msg);
}

sqlite3  *db  = NULL;

int get_channels(PARAM id, char *str){
    int      nrow=0,ncolumn=0;
    char     **azResult = NULL;
    char     *zErrMsg = 0;
    int      rc;
    char     sql[500];
    /* get phase channel */
    if( strcmp(id.value, "") != 0 && strcmp(id.value, "null") != 0 ){
        if(strcmp(id.value, "0") == 0)
            sprintf(sql, "select channel_index from [tb_channel_parm] where channel_ctrl_signal_source = -1 ");
        else
            sprintf(sql, "select channel_index from [tb_channel_parm] where channel_ctrl_signal_source = %s ", id.value);
    } 
    
    rc = sqlite3_get_table(db, sql, &azResult, &nrow, &ncolumn, &zErrMsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr,"SQL error:%s\n", zErrMsg);
        put_error(zErrMsg);
        sqlite3_close(db);
        return 0;
    } 
    if (*azResult != NULL) {
        char ch[500];
		int i=0, j=0, n=0;
	    //printf("{ \"rows\": \"%d\", \"data\": [", nrow);
        for(i=1; i<=nrow; i++) {
            //printf("{");
		    char *phaseIndex = {0};
            for(j=0; j<ncolumn; j++) {
			    if(j==0){
				    phaseIndex = azResult[ (i*ncolumn) + j ];
			    }
			    //printf("\"%s\": \"", azResult[j]);         // column name
                printf("%s", azResult[ (i*ncolumn) + j ]); // column value
               
                n++;
            }
            if(i == nrow)
			    printf(" ");
		    else
			    printf(", ");
        }
        //printf("]}"); 
    }
    return 0;
}


int main(void) {
    int      nrow=0,ncolumn=0;
    char     **azResult = NULL;
    char     *zErrMsg = 0;
    char     sql[500];
    char     *input;
    char     *req_method;
    int      rc;
/*
    if(isvalid_cookie()!=0){
        putError();
    	return 0;
	}
*/
    rc = sqlite3_open(PATH_DATABASE,&db);
    if (rc) {
        fprintf(stderr,"Can't open database:%s\n",sqlite3_errmsg(db));
        sqlite3_close(db);
        put_error((char*)sqlite3_errmsg(db));
        return 0;

    } else {

    	req_method = getenv("REQUEST_METHOD");

		FILE* fp = (FILE*) stdin;
	    input = getcgidata(fp, req_method);

	    PARAM id = getParam(input, "id");

	    PARAM dataType = getParam(input, "dataType");

	    if( strcmp(id.value, "") != 0 && strcmp(id.value, "null") != 0 ){
	        if(strcmp(id.value, "0") == 0)
			    sprintf(sql, "select * from [tb_phase_parm] where phase_index = -1 ");
			else
			    sprintf(sql, "select * from [tb_phase_parm] where phase_index = %s ", id.value);
		} else {
			 sprintf(sql, "select * from [tb_phase_parm]");
		}

        rc = sqlite3_get_table(db,sql,&azResult,&nrow,&ncolumn,&zErrMsg);
        if (rc != SQLITE_OK) {
            fprintf(stderr,"SQL error:%s\n", zErrMsg);
            put_error(zErrMsg);
            sqlite3_close(db);
            return 0;

        } 
         
        // choose data format
        if( strcmp(dataType.value, "json") == 0 ){
		 	//if (*azResult != NULL) {            
                 put_json(azResult, nrow, ncolumn);
            //} else {
            //    printf("Content-type:text/json;charset=UTF-8\n\n");
		    //    printf("%d %d\n",nrow, ncolumn);
            //}
		} else {
		    if (*azResult != NULL) {            
                 put_html(azResult, nrow, ncolumn);
            } else {
                printf("Content-type:text/html;charset=UTF-8\n\n");
            }
		}
    }

    sqlite3_close(db);
    return 0;

}

void put_json(char **azResult, int nrow, int ncolumn){
	int i=0, j=0, n=0;
	printf("Content-type:text/json;charset=UTF-8\n\n");
	printf("{ \"rows\": \"%d\", \"data\": [", nrow);
    for(i=1; i<=nrow; i++) {
        printf("{");
		char *phaseIndex = {0};
        for(j=0; j<ncolumn; j++) {
			if(j==0){
				phaseIndex = azResult[ (i*ncolumn) + j ];
				
				printf("\"%s\": \"", "lanes");
			    PARAM p;
                sprintf(p.value, "%s", azResult[ (i*ncolumn) + 0 ]);
                get_channels(p, NULL);
                printf("\",");
			}
			printf("\"%s\": \"", azResult[j]);

			if(j==9 || j==10){
				char t[100];
				printf("%s", _itoa(
							atoi(  azResult[ (i*ncolumn) + j ] ),
							t, 2) );
			} else if(strcmp(azResult[j], "green_flash_time") == 0){			   
			    printf("%.1f",  atof(azResult[ (i*ncolumn) + j ]) / 10 );
			} else {
				printf("%s", azResult[ (i*ncolumn) + j ]);
			}
            //printf(azResult[ (i*ncolumn) + j ]);

            if(j == ncolumn-1)
				printf("\"");
			else
				printf("\",");
            n++;
        }
        if(i == nrow)
			printf("}\n\n");
		else
			printf("},\n\n");
    }
    printf("]}");
}


void put_html(char **azResult, int nrow, int ncolumn){
	int i=0, j=0, n=0;
	printf("Content-type:text/html;charset=UTF-8\n\n");
	printf("<table res=\"%d\" id=\"phase\">", nrow);
    printf("<tr>\
		<th>相位序号</th>\
		<th>行人过街绿灯时长(秒)</th>\
		<th>行人清空时间(秒)</th>\
		<th>最小绿灯时间(秒)</th>\
		<th>单位绿灯延长时间(秒)</th>\
		<th>最大绿灯时间1(秒)</th>\
		<th>最大绿灯时间2(秒)</th>\
		<th>弹性相位固定绿灯时间(秒)</th>\
		<th>绿闪时间(秒)</th>\
		<th>相位类型</th>\
		<th>相位选项功能</th>\
		<th style=\"display:none;\">扩展</th>\
		<th>通道</th>\
		<th>修改时间</th>\
		<th>选项</th></tr>\n");
    for(i=1; i<=nrow; i++) {            
        printf("<tr>");
		char *phaseIndex = {0};
        for(j=0; j<ncolumn; j++) {
			if(j==0){
				phaseIndex = azResult[ (i*ncolumn) + j ];
			}
			printf("<td>");
			if(strcmp(azResult[j], "green_flash_time") ==0){			   
			    printf("%.1f",  atof(azResult[ (i*ncolumn) + j ]) / 10 );
			} else if(j==9 || j==10){
				char t[100];
				printf("%s", _itoa( atoi(azResult[(i*ncolumn) + j]), t, 2) );
			} else {
				printf("%s", azResult[ (i*ncolumn) + j ]);
			}
			
            printf("</td>");
            
            if(j == ncolumn-2){ // insert channels
                printf("<td>");
			    PARAM p;
                sprintf(p.value, "%s", azResult[ (i*ncolumn) + 0 ]);
                get_channels(p, NULL);
                printf("</td>");
            } 
            
            n++;
        }
        printf("<td>\
              		<input type=\"button\" class=\"edit-btn\" title=\"编辑\" onclick=\"editPhase(%s)\"/>\
              		<input type=\"button\" class=\"dele-btn\" title=\"删除\" onclick=\"deletePhase(%s)\" />\
              </td>", phaseIndex, phaseIndex);
        printf("<tr>\n\n");
    }
    printf("</table>");
}

